<!DOCTYPE html>
<html>
<head>
    <title>列表</title>
    <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/bootstrap-table/src/bootstrap-table.css">
    <link rel="stylesheet"
          href="https://cdn.bootcss.com/x-editable/1.5.1/bootstrap-editable/css/bootstrap-editable.css">
    <link rel="stylesheet" href="/assets/examples.css">
    <script src="/assets/jquery.min.js"></script>
    <script src="/assets/bootstrap/js/bootstrap.min.js"></script>
    <script src="/assets/ga.js"></script>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.min.js"></script>
    <![endif]-->
</head>
<body>
<div class="container">
    <div id="toolbar">
        <a href="/devices/detail?type={{.DeviceType}}"><button class="btn btn-primary " type="button"><i class="fa fa-plus"></i>&nbsp;添加</button></a>

        
        {{if eq .DeviceStatus 0}}<button id="remove" class="btn btn-danger" disabled>
            <i class="glyphicon glyphicon-remove"></i> Delete
        </button>{{end}}
        {{if ne .DeviceStatus 0}}<button id="status_0" class="btn btn-info" disabled>
            <i class="glyphicon glyphicon-remove"></i> 初始化
        </button>{{end}}
        {{if ne .DeviceStatus 1}}<button id="status_1" class="btn btn-info" disabled>
            <i class="glyphicon glyphicon-remove"></i> 正常运行
        </button>{{end}}
        {{if ne .DeviceStatus 2}}<button id="status_2" class="btn btn-info" disabled>
            <i class="glyphicon glyphicon-remove"></i> 维修检测
        </button>{{end}}
        {{if ne .DeviceStatus 3}}<button id="status_3" class="btn btn-info" disabled>
            <i class="glyphicon glyphicon-remove"></i> 故障
        </button>{{end}}
    </div>
    <table id="table"
           data-toolbar="#toolbar"
           data-search="true"
           data-show-refresh="true"
           data-show-toggle="true"
           data-show-columns="true"
           data-show-export="true"
           data-detail-view="false"
           data-detail-formatter="detailFormatter"
           data-minimum-count-columns="2"
           data-show-pagination-switch="true"
           data-pagination="true"
           data-id-field="id"
           data-page-list="[10, 25, 50, 100, ALL]"
           data-show-footer="false"
           data-side-pagination="server"
           data-url="/devices/list?DeviceStatus={{.DeviceStatus}}&DeviceType={{.DeviceType}}"
           data-response-handler="responseHandler">
    </table>
</div>

<script>
    var $table = $('#table'),
        {{if eq .DeviceStatus 0}}$remove = $('#remove'),{{end}}
        {{if ne .DeviceStatus 0}}$status_0 = $('#status_0'),{{end}}
        {{if ne .DeviceStatus 1}}$status_1 = $('#status_1'),{{end}}
        {{if ne .DeviceStatus 2}}$status_2 = $('#status_2'),{{end}}
        {{if ne .DeviceStatus 3}}$status_3 = $('#status_3'),{{end}}
        selections = [];

    function initTable() {
        $table.bootstrapTable({
            height: getHeight(),
            columns: [
                [
                    {
                        field: 'state',
                        checkbox: true,
                        rowspan: 2,
                        align: 'center',
                        valign: 'middle'
                    }, {
                    title: 'ID',
                    field: 'Id',
                    rowspan: 2,
                    align: 'center',
                    valign: 'middle',
                    sortable: true,
                    footerFormatter: totalTextFormatter
                }, {
                    title: '简要信息',
                    colspan: 6,
                    align: 'center'
                }
                ],
                [
                    {
                        field: 'DeviceName',
                        title: '设备名称',
                        sortable: true,
                        editable: false,
                        align: 'center'
                    },{
                        field: 'PointModule',
                        title: '抽奖模板编码',
                        sortable: true,
                        editable: false,
                        align: 'center'
                    },{
                        field: 'DeviceCreateTime',
                        title: '创建时间',
                        sortable: true,
                        editable: false,
                    formatter: function(value, row, index) {
                        return value.substring(0,value.indexOf("T"));
                    },
                        align: 'center'
                    },{
                        field: 'DeviceStatus',
                        title: '设备状态',
                        sortable: true,
                        editable: false,
                    formatter: function(value, row, index) {
                        if (value == "0") {
                            return "初始化";
                        }
                        if (value == "1") {
                            return "正常运行";
                        }
                        if (value == "2") {
                            return "维修检测";
                        }
                        if (value == "3") {
                            return "故障";
                        }
                        
                        return "?";
                    },
                        align: 'center'
                    },{
                        field: 'DevicePosition',
                        title: '地点编号',
                        sortable: true,
                        editable: false,
                        align: 'center'
                    }, {
                    field: 'operate',
                    title: 'Item Operate',
                    align: 'center',
                    events: operateEvents,
                    formatter: operateFormatter
                }
                ]
            ]
        });
        // sometimes footer render error.
        setTimeout(function () {
            $table.bootstrapTable('resetView');
        }, 200);
        $table.on('check.bs.table uncheck.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            
            {{if eq .DeviceStatus 0}}$remove.prop('disabled', !$table.bootstrapTable('getSelections').length);{{end}}
            {{if ne .DeviceStatus 0}}$status_0.prop('disabled', !$table.bootstrapTable('getSelections').length);{{end}}
            {{if ne .DeviceStatus 1}}$status_1.prop('disabled', !$table.bootstrapTable('getSelections').length);{{end}}
            {{if ne .DeviceStatus 2}}$status_2.prop('disabled', !$table.bootstrapTable('getSelections').length);{{end}}
            {{if ne .DeviceStatus 3}}$status_3.prop('disabled', !$table.bootstrapTable('getSelections').length);{{end}}

            // save your data, here just save the current page
            selections = getIdSelections();
            // push or splice the selections if you want to save all data selections
        });
        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
            if (index % 2 == 1) {
                $detail.html('Loading from ajax request...');
                $.get('LICENSE', function (res) {
                    $detail.html(res.replace(/\n/g, '<br>'));
                });
            }
        });
        $table.on('all.bs.table', function (e, name, args) {
            console.log(name, args);
        });
        
	{{if eq .DeviceStatus 0}}$remove.click(function () {
            var ids = getIdSelections();
            $.post("/devices/delete", {Id: ids}, function (data) {
                alert(data.Data);
                if (data.Code == 1) {
                    $table.bootstrapTable('remove', {
                        field: 'Id',
                        values: ids
                    });
                }
            }, "json");
	});{{end}}
	{{if ne .DeviceStatus 0}}$status_0.click(function () {
            var ids = getIdSelections();
            $.post("/devices/changestatus", {Id: ids,ChangedStatus:0}, function (data) {
                alert(data.Data);
                if (data.Code == 1) {
                    $table.bootstrapTable('remove', {
                        field: 'Id',
                        values: ids
                    });
                }
            }, "json");
	});{{end}}
	{{if ne .DeviceStatus 1}}$status_1.click(function () {
            var ids = getIdSelections();
            $.post("/devices/changestatus", {Id: ids,ChangedStatus:1}, function (data) {
                alert(data.Data);
                if (data.Code == 1) {
                    $table.bootstrapTable('remove', {
                        field: 'Id',
                        values: ids
                    });
                }
            }, "json");
	});{{end}}
	{{if ne .DeviceStatus 2}}$status_2.click(function () {
            var ids = getIdSelections();
            $.post("/devices/changestatus", {Id: ids,ChangedStatus:2}, function (data) {
                alert(data.Data);
                if (data.Code == 1) {
                    $table.bootstrapTable('remove', {
                        field: 'Id',
                        values: ids
                    });
                }
            }, "json");
	});{{end}}
	{{if ne .DeviceStatus 3}}$status_3.click(function () {
            var ids = getIdSelections();
            $.post("/devices/changestatus", {Id: ids,ChangedStatus:3}, function (data) {
                alert(data.Data);
                if (data.Code == 1) {
                    $table.bootstrapTable('remove', {
                        field: 'Id',
                        values: ids
                    });
                }
            }, "json");
	});{{end}}
        $(window).resize(function () {
            $table.bootstrapTable('resetView', {
                height: getHeight()
            });
        });
    }

    function getIdSelections() {
        return $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.Id
        });
    }

    function responseHandler(res) {
        $.each(res.rows, function (i, row) {
            row.state = $.inArray(row.id, selections) !== -1;
        });
        return res;
    }

    function detailFormatter(index, row) {
        var html = [];
        $.each(row, function (key, value) {
            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
        });
        return html.join('');
    }
    function operateFormatter(value, row, index) {
        return [
            '<a class="like" href="javascript:void(0)" title="Like">',
            '<button class="btn btn-sm btn-default">浏览</button>',
            '</a>  ',
            '<a class="edit" href="javascript:void(0)" title="Remove">',
            '<button class="btn btn-sm btn-success">编辑</button>',
            '</a>'
        ].join('');
    }
    window.operateEvents = {
        'click .like': function (e, value, row, index) {

        },
        'click .edit': function (e, value, row, index) {
            window.location.href="/devices/detail?Id="+row.Id;
        }
    };



    function totalTextFormatter(data) {
        return 'Total';
    }

    function totalNameFormatter(data) {
        return data.length;
    }

    function totalPriceFormatter(data) {
        var total = 0;
        $.each(data, function (i, row) {
            total += +(row.price.substring(1));
        });
        return '$' + total;
    }

    function getHeight() {
        return $(window).height() - $('h1').outerHeight(true);
    }

    $(function () {
        var scripts = [
                location.search.substring(1) || '/assets/bootstrap-table/src/bootstrap-table.js',
                '/assets/bootstrap-table/src/extensions/export/bootstrap-table-export.js',
                'https://cdn.bootcss.com/TableExport/5.0.0-rc.11/js/tableexport.js',
                '/assets/bootstrap-table/src/extensions/editable/bootstrap-table-editable.js',
                'https://cdn.bootcss.com/x-editable/1.5.1/bootstrap-editable/js/bootstrap-editable.js',
                '/lang/zh-cn/bootstrap-table-zh-CN.js'
            ],
            eachSeries = function (arr, iterator, callback) {
                callback = callback || function () {
                    };
                if (!arr.length) {
                    return callback();
                }
                var completed = 0;
                var iterate = function () {
                    iterator(arr[completed], function (err) {
                        if (err) {
                            callback(err);
                            callback = function () {
                            };
                        }
                        else {
                            completed += 1;
                            if (completed >= arr.length) {
                                callback(null);
                            }
                            else {
                                iterate();
                            }
                        }
                    });
                };
                iterate();
            };

        eachSeries(scripts, getScript, initTable);
    });

    function getScript(url, callback) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = url;

        var done = false;
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState ||
                this.readyState == 'loaded' || this.readyState == 'complete')) {
                done = true;
                if (callback)
                    callback();

                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null;
            }
        };

        head.appendChild(script);

        // We handle everything using the script element injection
        return undefined;
    }
</script>
</body>
</html>